package com.oreilly.ez.base;

import com.auth0.jwt.interfaces.Claim;
import com.oreilly.ez.util.JwtToken;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

public class SysInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //普通路径放行
        String uri = request.getRequestURI();
        System.out.println("url = " + uri);




        Cookie[] cookies = request.getCookies();

//        for (Cookie cookie : cookies) {
//            System.out.println(String.format("cookie: {%s -> %s}", cookie.getName(), cookie.getValue()));
//        }

        if(cookies != null){

            for (Cookie cookie : cookies) {

                if(cookie.getName().equals("X-Authorization")){
                    String token = cookie.getValue();
                    String appUID = JwtToken.getAppUID(token);
//                System.out.println("appUID" + appUID);

                    if(appUID != null && appUID.length()>0){

                        if(uri.equals("/login.html") || uri.equals("/index.html") || uri.equals("/toLogin")){
                            response.sendRedirect("/appHome");
                        }
                        return true;

                    }
                }
            }
        }



        if(uri.endsWith(".css") || uri.endsWith(".js") || uri.endsWith(".png") ||
                uri.contains("browser/index.html#/")|| uri.endsWith(".eot") ||
                uri.endsWith(".ttf") || uri.endsWith(".woff") ||
                uri.equals("/toLogin") || uri.equals("/login.html") ||
                uri.equals("/login")

                ){



            return true;
        }


        response.sendRedirect("/toLogin");
        return false;

//        if ("/login".equals(uri) || "/index.html".equals(uri) ||
//            "/toLogin".equals(uri) || "/fail.html".equals(uri)) {
//            return true;
//        }

        //权限路径拦截
//        Object object = request.getSession().getAttribute("USER");
//        if (null == object) {
//            response.sendRedirect("/toLogin");
//            return false;
//        }

//        response.sendRedirect("/toLogin");
//        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {

    }
}
